package com.smartum.mpr.business;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.smartum.mpr.dao.NewsDao;
import com.smartum.mpr.dao.UserDao;
import com.smartum.mpr.exception.DatabaseIntegrityException;
import com.smartum.mpr.exception.NotExistsTokenException;
import com.smartum.mpr.model.News;
import com.smartum.mpr.model.NewsImage;
import com.smartum.mpr.model.User;
import com.smartum.mpr.util.BackendConfig;

@Service
public class NewsBusiness extends BaseBusiness {

	@Autowired
	NewsDao newsDao;
	@Autowired
	UserDao userDao;

	public void saveNews(String token, News news) throws DatabaseIntegrityException, NotExistsTokenException {
		User user = userDao.findUserByToken(token);
		news.setOwner(user);
		news.setTimeStamp(System.currentTimeMillis());
		newsDao.save(news);
	}

	
	public void updateNews(String token, News news) throws DatabaseIntegrityException, NotExistsTokenException {
		User user = userDao.findUserByToken(token);
		news.setOwner(user);
		news.setTimeStamp(System.currentTimeMillis());
		newsDao.save(news);
	}

	
	
	public List<News> getPublicNews(long timestamp, int amount) {
		List<News> news = newsDao.getPublicNews(timestamp, amount);
		for (News newsItem : news) {
			changeImagePathInNews(newsItem);
		}

		return news;
	}

	public int getNewsCount() {
		return newsDao.getList().size();
	}

	

	public News getNewsById(Long id) {
		News news = newsDao.get(id);
		changeImagePathInNews(news);
		return news;
	}

	public void removeNewsById(String token, Long id) throws DatabaseIntegrityException, NotExistsTokenException {
		userDao.findUserByToken(token);
		newsDao.delete(id);
	}

	private void changeImagePathInNews(News news) {
		String appUrl = BackendConfig.getInstance().getAppUrl();
		NewsImage image = news.getImage();
		if(image!=null){
			String imagePath = image.getImagePath();
			image.setImagePath(appUrl + imagePath);
			String littleImagePath = image.getLittleImagePath();
			image.setLittleImagePath(appUrl+littleImagePath);
			news.setImage(image);
		}
	}

}
